package net.mayee.alice.web.controller.validator.account;

import net.mayee.alice.entity.admin.account.Role;
import net.mayee.alice.web.controller.validator.base.BaseValidator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

public class RoleValidator extends BaseValidator implements Validator {

	private static final Pattern ROLE_KEY_PATTERN = Pattern
			.compile("^([a-zA-Z0-9]{4,20})$");

	@Override
	public boolean supports(Class<?> clazz) {
		return Role.class == clazz;
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "roleKey", "[ 唯一标识 ] 是必填项");
		ValidationUtils.rejectIfEmpty(errors, "name", "[ 名称 ] 是必填项");

		Role role = (Role) target;

		if (!ROLE_KEY_PATTERN.matcher(role.getRoleKey()).matches()) {
			errors.rejectValue("roleKey", "[ 唯一标识 ] 只能包含大小写字母和数字，长度在4 ~ 20个字符之间;");
		}

		String name = role.getName().trim();
		if (name.length() < 2 || name.length() > 20) {
			errors.rejectValue("name", "[ 名称 ] 长度在2 ~ 20个字符之间;");
		}

	}

}
